package com.hq.config;

import com.hq.mapper.UserMapper;
import com.hq.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserMapper userMapper;

    //授权信息----身份信息交给shiro后从中拿到授权信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        /*
        *如果身份验证时候传入的是用户信息 这里用对象接受
        * User user = (User) principalCollection.getPrimaryPrincipal();
        * 如果身份验证传入的是用户名，用String接受
        * String username = (String) principalCollection.getPrimaryPrincipal();
         */
        String username = (String) principalCollection.getPrimaryPrincipal();
        //根据用户名查询用户的权限
        Set<String> perms = userMapper.queryPermsByUsername(username);
        //根据用户名查询用户的角色
        Set<String> roles = userMapper.queryRolesByUsername(username);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(perms);
        info.setRoles(roles);
        return info;
    }
    //身份信息交给shiro
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //token里有前端传入的用户信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        User user = userMapper.queryUserByUsername(username);
        if(user == null){
            throw new UnknownAccountException("用户不存在");
        }
        if(!user.getPassword().equals(token.getPassword())){
            throw new UnknownAccountException("用户密码错误");
        }
        if(user.getStatus()==0){
            throw new UnknownAccountException("账户锁定，请联系管理员");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username,//可以传用户信息，可以传用户名
                user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()), //如果加盐了，需要加上该方法
                getName());
        return info;
    }
}
